#!/bin/sh
#服务器默认的脚本

#根目录，可以根据实际情况进行修改
export SERVER=/app

if [ -z "$APP_NAME" ]; then
  export APP_NAME="*.jar"
fi

if [ -z "$RUN_ARGS" ]; then
  export RUN_ARGS="--spring.config.location=$SERVER/conf/application.yml"
fi

#java虚拟机启动参数
#注意 Xms Xmx Xmn 三者的实际参数
if [ -z "$JAVA_OPTS" ]; then
  export JAVA_OPTS="-Xms256m -Xmx512m -Xmn128m -Xss1m \
  -XX:+HeapDumpOnOutOfMemoryError \
  -XX:+AggressiveOpts \
  -XX:+UseBiasedLocking \
  -XX:+UseParallelGC \
  -XX:+UseParallelOldGC \
  -XX:+UseAdaptiveSizePolicy \
  -XX:+PrintGCDetails \
  -XX:+PrintGCDateStamps \
  -Xloggc:logs/gc.log"
fi

export JAVA_OPTS="-server -Duser.timezone=UTC+08:00 -Djava.security.egd=file:/dev/./urandom -Djava.awt.headless=true -Dfile.encoding=utf-8 $JAVA_OPTS"

if [ -z "$JAVA_HOME" ] && [ -z "$JRE_HOME" ]; then
  echo "Neither the JAVA_HOME nor the JRE_HOME environment variable is defined"
  echo "At least one of these environment variables is needed to run this program"
  exit 1
fi

if [ -z "$JRE_HOME" ]; then
  JRE_HOME="$JAVA_HOME"
fi

if [ -z "$RUN_JAVA" ]; then
  export RUN_JAVA="$JRE_HOME/bin/java"
fi

start() {
  LOG=$SERVER/logs/all.log
  echo "start project begin..."
  echo $APP_NAME >>$LOG
  cd $SERVER
  classPath="."

  #nohup $RUN_JAVA $JAVA_OPTS -jar $SERVER/$APP_NAME $RUN_ARGS > /dev/null 2>&1 &
  echo "$RUN_JAVA $JAVA_OPTS -jar $SERVER/$APP_NAME $RUN_ARGS"
  exec $RUN_JAVA $JAVA_OPTS -jar $SERVER/$APP_NAME $RUN_ARGS

  echo $! >$SERVER/server.pid
  echo $(cat "$SERVER/server.pid")
  echo "start project end..."
}

stop() {
  echo "stop project..."
  if [ -f "$SERVER/server.pid" ]; then
    echo $(cat "$SERVER/server.pid")
    PID=$(cat "$SERVER/server.pid")
    kill -9 $PID >/dev/null 2>&1
    rm -rf $SERVER/server.pid
  fi
  if [ $(ps -ef | grep $SERVER | grep -v sh | grep -v grep | wc -l) -ne 0 ]; then
    echo "stop project: kill -9 $SERVER"
    ps -ef | grep $SERVER | grep -v sh | grep -v grep | awk {'print $2'} | xargs kill -9
  fi
  echo "stop project end..."
}

restart() {
  stop
  sleep 20
  start
}

if [ "$1" = "start" ]; then
  start
elif [ "$1" = "stop" ]; then
  stop
elif [ "$1" = "restart" ]; then
  restart
else
  restart
fi
